package com.five.taotao.product_details;


import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Message;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.five.taotao.Adapter.VPFregmentAdapter;
import com.five.taotao.Application.MyApplication;
import com.five.taotao.R;
import com.five.taotao.dao.ProductListBeanDao;
import com.five.taotao.entity.Product;
import com.five.taotao.entity.ShoppingCart;
import com.five.taotao.guide.GuideActivity;
import com.five.taotao.guide.HomeFragment;
import com.five.taotao.guide_mine.ShopCarActivity;
import com.five.taotao.login.LoginActivity;
import com.five.taotao.order_details.OrderConfirmActivity;
import com.five.taotao.util.Constants;
import com.google.gson.Gson;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

public class ProductDetailsActivity extends AppCompatActivity {


    @BindView(R.id.img1)
    ImageView img1;
    @BindView(R.id.img2)
    ImageView img2;
    @BindView(R.id.name_pro)
    TextView name_pro;
    @BindView(R.id.renminbi)
    TextView renminbi;
    @BindView(R.id.price)
    TextView price;
    @BindView(R.id.back)
    ImageView back;
    @BindView(R.id.collect)
    ImageView collect;
    @BindView(R.id.share)
    ImageView share;
    @BindView(R.id.more)
    ImageView more;
    @BindView(R.id.radiogroup)
    RadioGroup radiogroup;
    @BindView(R.id.tabs)
    TabLayout tabs;
    @BindView(R.id.vp)
    ViewPager vp;
    @BindView(R.id.custom)
    TextView custom;

    private String userid;
    private SharedPreferences sp;

    @OnClick(R.id.back)
    public void onClick() {
        finish();
    }

    @OnClick(R.id.shop_cart)
    public void shop_cart() {

        if(userid==""){
            Intent intent = new Intent(this, LoginActivity.class);
            startActivity(intent);
        }else{
            Intent intent = new Intent(this, ShopCarActivity.class);
            startActivity(intent);
        }
    }

    //客服
    @OnClick(R.id.custom)
    public void custom() {
        if(userid==""){
            Intent intent = new Intent(this, LoginActivity.class);
            startActivity(intent);
        }else{
            Intent intent = new Intent(this, CustomerServiceActivity.class);
            startActivity(intent);
        }

    }

    private Product.ListBean product;
    private VPFregmentAdapter fAdapter;//定义adapter
    private List<Fragment> list_fragment;//定义要装fragment的列表
    private List<String> list_title;   //tab名称列表
    private DetailsFragment detailsFragment;
    private RecommenFragment recommenFragment;
    private EvaluationFragment evaluationFragment;
    private ProductListBeanDao dao;
    private boolean isCollec = false;//默认没有收藏

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_product_details);
        ButterKnife.bind(this);
        dao = new ProductListBeanDao(this);
        product = (Product.ListBean) getIntent().getSerializableExtra("product");
        if (product != null) {
            initControls();
            collect.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Toast toast = new Toast(ProductDetailsActivity.this);
                    View view = LayoutInflater.from(ProductDetailsActivity.this).inflate(R.layout.self_toast, null, false);
                    TextView textView = (TextView) view.findViewById(R.id.show);

                    if(userid==""){
                        Intent intent=new Intent(ProductDetailsActivity.this,LoginActivity.class);
                        startActivity(intent);
                    }else{
                        if (isCollec == false) {
                            textView.setText("收藏成功");
                            toast.setView(view);
                            toast.setGravity(Gravity.CENTER, 0, 0);
                            toast.show();
                            product.setCollected(1);
                            collect.setImageResource(R.drawable.icon_fav_red);
                    /*//加载动画资源，生成动画对象
                    Animation animation = AnimationUtils.loadAnimation(this, R.anim.myanim);
                    love.startAnimation(animation);*/
                            isCollec = true;//已经收藏
                        } else {
                            textView.setText("取消收藏");
                            toast.setView(view);
                            toast.setGravity(Gravity.CENTER, 0, 0);
                            toast.show();
                            product.setCollected(0);
                            collect.setImageResource(R.drawable.icon_no_fav_gray);
                            isCollec = false;//取消收藏
                        }
                    }


                }
            });
        }

    }

    @Override
    protected void onStart() {
//        sp=getSharedPreferences("user",MODE_PRIVATE);
//        userid=sp.getString("userId","");
        userid=MyApplication.userId;
        super.onStart();
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (!dao.findProduct(product.getProductId())) {
            dao.addProduct(product);
        }

    }

    /**
     * 初始化各控件
     *
     * @param
     */
    private void initControls() {

        Glide.with(this)
                .load(product.getUrl())
                .placeholder(R.drawable.store_default1)//占位图片
                .error(R.drawable.store_default1)
                .thumbnail(0.5f)
                .into(img1);
        price.setText(product.getPrice() + "");
        name_pro.setText(product.getName());

        //初始化各fragment
        detailsFragment = new DetailsFragment();
        evaluationFragment = new EvaluationFragment();
        recommenFragment = new RecommenFragment();

        //将fragment装进列表中
        list_fragment = new ArrayList<>();
        list_fragment.add(detailsFragment);
        list_fragment.add(evaluationFragment);
        list_fragment.add(recommenFragment);

        //将名称加载tab名字列表，正常情况下，我们应该在values/arrays.xml中进行定义然后调用
        list_title = new ArrayList<>();
        list_title.add("详情");
        list_title.add("评论");
        list_title.add("推荐");
        //设置TabLayout的模式
        tabs.setTabMode(TabLayout.MODE_FIXED);

        fAdapter = new VPFregmentAdapter(getSupportFragmentManager(), list_fragment, list_title);
        vp.setAdapter(fAdapter);
        tabs.setupWithViewPager(vp);

    }

    //分享
    @OnClick(R.id.share)
    public void share(View v) {
        if(userid==""){//未登录
            Intent intent=new Intent(this, LoginActivity.class);
            startActivity(intent);
        }else{
            pupupwindow2(v);
        }
    }

    //更多
    @OnClick(R.id.more)
    public void more(View v) {
        pupupwindow3(v);
    }

    //加入购物车
    @OnClick(R.id.item3)
    public void addShopCart(View v) {
        if(userid==""){
            Intent intent=new Intent(this, LoginActivity.class);
            startActivity(intent);
        }else{
            popupwindow("加入购物车");
        }
    }

    //立即购买
    @OnClick(R.id.item4)
    public void buy(View v) {
        if(userid==""){
            Intent intent=new Intent(this, LoginActivity.class);
            startActivity(intent);
        }else{
            popupwindow("立即购买");
        }

    }

    public void pupupwindow3(View v) {

        View view = LayoutInflater.from(this).inflate(R.layout.more_product_details, null, false);
        final PopupWindow popupWindow = new PopupWindow(view
                , ViewGroup.LayoutParams.WRAP_CONTENT,
                250);
        view.findViewById(R.id.home).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(ProductDetailsActivity.this, GuideActivity.class);
                startActivity(intent);
            }
        });
        view.findViewById(R.id.msg).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(ProductDetailsActivity.this, MessageActivity.class);
                startActivity(intent);

            }
        });

        popupWindow.setFocusable(true);
        popupWindow.setOutsideTouchable(true);
        popupWindow.setBackgroundDrawable(new BitmapDrawable());
        int xOff = popupWindow.getWidth() / 2 - view.getWidth() / 2;
        /**
         * 显示基准控件下面
         * view 基准控件
         * -xOff view左边到pop左边的偏移量
         * 0 view下边到pop上面的偏移量
         */
        WindowManager windowManager = (WindowManager) this.getSystemService(Context.WINDOW_SERVICE);
        popupWindow.showAsDropDown(view, windowManager.getDefaultDisplay().getWidth() - view.getWidth() - 280, 220);

    }


    public void pupupwindow2(View v) {
        {
            View view = LayoutInflater.from(this).inflate(R.layout.share_product_details, null, false);
            final PopupWindow popupWindow = new PopupWindow(view
                    , ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT);
            view.findViewById(R.id.close).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    popupWindow.dismiss();
                }
            });


            //6.0以下点击popupWindow外边空白，popupWindow消失的操作
            popupWindow.setFocusable(true);
            popupWindow.setOutsideTouchable(true);
            ColorDrawable colorDrawable = new ColorDrawable(0);
            popupWindow.setBackgroundDrawable(colorDrawable);

            //设置动画效果
            popupWindow.setAnimationStyle(R.style.pop_anim);
            popupWindow.showAtLocation(view, Gravity.BOTTOM, 0, 0);


            WindowManager.LayoutParams lp = getWindow().getAttributes();
            lp.alpha = 0.4f;
            getWindow().setAttributes(lp);

            /**
             * 设置监听
             */
            popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
                @Override
                public void onDismiss() {
                    WindowManager.LayoutParams lp = getWindow().getAttributes();
                    lp.alpha = 1.0f;
                    getWindow().setAttributes(lp);
                }
            });
        }

    }

    //购物弹框
    public void popupwindow(String v) {
        View view = LayoutInflater.from(this).inflate(R.layout.shoppingcart, null, false);
        final PopupWindow popupWindow = new PopupWindow(view
                , ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT);
        view.findViewById(R.id.img).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
            }
        });

        ImageView img = (ImageView) view.findViewById(R.id.img);
        TextView name = (TextView) view.findViewById(R.id.name);
        TextView price = (TextView) view.findViewById(R.id.price);
        TextView num = (TextView) view.findViewById(R.id.num);
        final TextView tv_shopcar_count = (TextView) view.findViewById(R.id.tv_shopcar_count);
        final int[] count = {Integer.parseInt(tv_shopcar_count.getText().toString())};

        final TextView add_order = (TextView) view.findViewById(R.id.add_order);
        add_order.setText(v);
        add_order.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String tmp = add_order.getText().toString();
                if (count[0] == 0) {
                    MyApplication.toast.toastShow("数量不能为0");
                } else {
                    if (tmp.equals("加入购物车")) {
                        popupWindow.dismiss();
                        OkHttpUtils
                                .post()
                                .url(Constants.AC_URL)
                                .addParams("userid", MyApplication.userId)
                                .addParams("goodid", product.getProductId())
                                .addParams("num", count[0] + "")
                                .build()
                                .execute(new StringCallback() {
                                    @Override
                                    public void onError(Call call, Exception e, int id) {
                                    }

                                    @Override
                                    public void onResponse(String response, int id) {
                                        Toast toast = new Toast(ProductDetailsActivity.this);
                                        View view = LayoutInflater.from(ProductDetailsActivity.this).inflate(R.layout.self_toast, null, false);
                                        TextView textView = (TextView) view.findViewById(R.id.show);
                                        textView.setText("添加成功");
                                        toast.setView(view);
                                        toast.setGravity(Gravity.CENTER, 0, 0);
                                        toast.show();
                                    }
                                });
                    } else if (tmp.equals("立即购买")) {
                        Intent intent = new Intent(ProductDetailsActivity.this, OrderConfirmActivity.class);
                        ShoppingCart.ListBean shopcar = new ShoppingCart.ListBean(
                                product.getName(),product.getPrice(),product.getIntroduce(),product.getUrl(),(int)product.getVipprice(),
                                product.getSid1(),product.getPid1(),product.getStock(),Integer.parseInt(product.getProductId()));
                        shopcar.setNum(count[0]);
                        intent.putExtra("shopcar", shopcar);
                        startActivity(intent);
                    }

                }

            }
        });

        view.findViewById(R.id.delete).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (--count[0] < 0) {
                    MyApplication.toast.toastShow("数量不能为0");
                    count[0] = 0;
                    return;
                }
                tv_shopcar_count.setText(count[0] + "");
            }
        });
        view.findViewById(R.id.add).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                tv_shopcar_count.setText(++count[0] + "");
            }
        });

        Glide.with(this)
                .load(product.getUrl())
                .placeholder(R.drawable.store_default1)//占位图片
                .error(R.drawable.store_default1)
                .thumbnail(0.5f)
                .into(img);
        name.setText(product.getName());
        price.setText("￥: " + product.getPrice());
        num.setText("库存: " + product.getStock());

        //6.0以下点击popupWindow外边空白，popupWindow消失的操作
        popupWindow.setFocusable(true);
        popupWindow.setOutsideTouchable(true);
        ColorDrawable colorDrawable = new ColorDrawable(0);
        popupWindow.setBackgroundDrawable(colorDrawable);

        //设置动画效果
        popupWindow.setAnimationStyle(R.style.pop_anim);
        popupWindow.showAtLocation(view, Gravity.BOTTOM, 0, 0);

        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = 0.4f;
        getWindow().setAttributes(lp);

        /**
         * 设置监听
         */
        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                WindowManager.LayoutParams lp = getWindow().getAttributes();
                lp.alpha = 1.0f;
                getWindow().setAttributes(lp);
            }
        });
    }

//    /**
//     * 跳转界面公用方法
//     * @param
//     */
//    private void startLoginedorLogoutedActivity(Class clzssin,Class clzssout){
//        Intent intent;
//        userid=sp.getString("userId","");
//        if(userid==""){//未登录
//            intent=new Intent(this,clzssout);
//            startActivity(intent);
//        }else{//已经登录
//            intent=new Intent(this,clzssin);
//            startActivity(intent);
//        }
//    }
}
